#include "Polynomial.h"


Polynomial::Polynomial() 
{
}

Polynomial Polynomial::operator+( const Polynomial & rhs ) const
{
    Polynomial sum;

	sum._degree = max( degree(), rhs.degree() );

    for( int i = sum.degree(); i >= 0; --i )
	{
		double a = i <= degree() ? _coefficients[i] : 0; // ignore compiler warning, signed/unsigned mismatch
		double b = i <= rhs.degree() ? rhs._coefficients[i] : 0;
		 
		sum.setCoefficient(i, a + b); 
	}
    return sum;
}

void Polynomial::print( ostream & out ) const
{
    for( int i = degree(); i > 0; i-- )
		out << _coefficients[ i ] << "x^" << i << " + ";
    
	out << _coefficients[ 0 ] << endl;
}

double Polynomial::evaluate(double x) const
{
	double p = 0;
	for ( int i = degree(); i >= 0; i-- )
		p = _coefficients[i] + ( x * p );
	return p;
}

void Polynomial::setCoefficient( size_t k, double val )
{
	if(k < _coefficients.size())
		_coefficients[k] = val;
	else
	{
		_degree = k;
		for(size_t j = _coefficients.size(); j < degree(); j++)
		{
			_coefficients.push_back(0);
		}
		_coefficients.push_back(val);
	}
}

Polynomial Polynomial::operator*( const Polynomial & rhs ) const
{
	const Polynomial&lhs = *this; 
	
	Polynomial c;
	for ( int i = 0; i <= lhs.degree(); i++ ){
		for ( int j = 0; j <= rhs.degree(); j++ ){
			double coefficient = c.getCoefficient(i+j);
			c.setCoefficient(i+j, coefficient + (lhs.getCoefficient(i) * rhs.getCoefficient(j)));
		}
	}
	return c;
}

Polynomial Polynomial::operator*( const double rhs ) const
{
	Polynomial c;
	const Polynomial&lhs = *this; 

	for ( int i = 0; i <= lhs.degree(); i++ ){
		c.setCoefficient(i, lhs.getCoefficient(i)*rhs);
	}
	return c;
}
